package network.socket;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Vector;

import network.RSocket;

import tools.Help;
public class TCPServer extends Thread {
	private ServerSocket sock;
	private Vector<TCPClient> clients;
	private boolean running;
	private int lastnew;
	public TCPServer(int port) {
		super();
		try {
			sock = new ServerSocket(port);
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(1);
		}
		clients = new Vector<TCPClient>();
		running = true;
		lastnew = 0;
		this.start();
	}
	public void run() {
		while (running) {
			try {
				sock.setSoTimeout(100);
				Socket s = sock.accept();
				this.addClient(s);
			} catch (IOException e) {
			}
		}
	}
	private void addClient(Socket s) {
		String add = s.getInetAddress().toString();
		int p = s.getPort();
		for (TCPClient c : clients) {
			if (c.address.equals(add) && c.port == p) {
				return;
			}
		}
		Help.p("new client connected: " + add + ":" + p);
		clients.add(new TCPClient(s));
	}
	public void send(byte b[], int client) {
		TCPClient c = clients.get(client);
		c.send(b);
	}
	public byte[] receive(int client) {
		TCPClient c = clients.get(client);
		return c.getReceiveData();
	}
	public int getNumSockets() {
		return clients.size();
	}
	public void close() {
		this.running = false;
		try {
			this.join();
			sock.close();
		} catch (InterruptedException e) {
		} catch (IOException e) {
		}
	}
	public Vector<Integer> getNewClients() {
		Vector<Integer> newc = new Vector<Integer>();
		for (int i = lastnew; i < clients.size(); i++) {
			newc.add(i);
		}
		lastnew = clients.size();
		return newc;
	}
	public RSocket getClientSocket(int cid) {
		return clients.get(cid);
	}
}
